package com.ruoyi.web.controller.client;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.yf.domain.YfDept;
import com.ruoyi.yf.domain.YfTag;
import com.ruoyi.yf.domain.mobile.*;
import com.ruoyi.yf.service.IYfDeptService;
import com.ruoyi.yf.service.IYfTagService;
import com.ruoyi.yf.tool.barcode.Rules;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * LXL
 * 接口 - 秦皇岛妇幼医废出入库操作页面接口
 */
@Controller
@RequestMapping("/client")
public class HtmlController extends BaseController {

    @Autowired
    IYfTagService yfTagService;     // 医废

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IYfDeptService yfDeptService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService userService;


    // 出入库主页
    //1b7bfab9-e2c6-4b4e-ad1c-9d250fd327b0
    @GetMapping("/qinoutstore")
    public String main() {
        return "qinoutstore/main";
    }

    // 入库
    //5b9eeb47-f324-40a8-83ac-c0f2b8f709bf
    @GetMapping("/inStore")
    public String inStore() {
        return "qinoutstore/inStore";
    }


    // 出库
    //a2099217-11ac-4d71-a8cb-1d8aaea88cd6
    @GetMapping("/outStore")
    public String outStore() {
        return "qinoutstore/outStore";
    }


    // 旧平台医废数据迁移到新平台接口
    //92ebe814-686a-4421-a959-0a77115d2969
    @GetMapping("/dataMigration")
    @ResponseBody
    public String dataMigration() {

        // 黄骅神农居医院    医院id：262      暂存点id：263
        // 神农居用户：
        // 135    mgy1       111111      采集
        // 136    mgy2       222222      入库
        // 137    mgy3       333333      出库
        // 138    zyj         111111      巡检
        // 139    zhangyj     111111      医院管理员


        // 沧州疾控中心    医院id：304      暂存点id：305
        // 沧州疾控中心用户：
        // 395    czjklsz1       111111      采集
        // 396    czjkwhf1       111111      入库
        // 397    czjkwhf2       111111      出库



        // 拼接科室SQL
        // select CONCAT('kslist.add( new DepartmentIdSwitch( "',od.departid,'",',d.dept_id,'L,','"',d.dept_name,'" ) );') as zd,
        // od.departid,d.dept_id,d.dept_name
        // from yf_dept d
        // LEFT JOIN department od on od.departname = d.dept_name
        // where d.hospital_id = '262'
        List<DepartmentIdSwitch> kslist = new ArrayList<>();
        // 黄骅神农居医院科室
//        kslist.add( new DepartmentIdSwitch( "001",20200611115201L,"急诊科" ) );
//        kslist.add( new DepartmentIdSwitch( "002",20200611115301L,"骨科门诊" ) );
//        kslist.add( new DepartmentIdSwitch( "003",20200611115401L,"中医皮肤专业" ) );
//        kslist.add( new DepartmentIdSwitch( "004",20200611115501L,"一楼中医" ) );
//        kslist.add( new DepartmentIdSwitch( "005",20200611115601L,"口腔科" ) );
//        kslist.add( new DepartmentIdSwitch( "006",20200611115801L,"耳鼻喉科" ) );
//        kslist.add( new DepartmentIdSwitch( "007",20200611115901L,"眼科" ) );
//        kslist.add( new DepartmentIdSwitch( "008",20200611120001L,"妇科门诊" ) );
//        kslist.add( new DepartmentIdSwitch( "009",20200611120101L,"胃镜室" ) );
//        kslist.add( new DepartmentIdSwitch( "010",20200611120201L,"彩超室" ) );
//        kslist.add( new DepartmentIdSwitch( "011",20200611120301L,"体检科" ) );
//        kslist.add( new DepartmentIdSwitch( "012",20200611120401L,"放射科" ) );
//        kslist.add( new DepartmentIdSwitch( "013",20200611120402L,"儿科" ) );
//        kslist.add( new DepartmentIdSwitch( "014",20200611120502L,"儿科大厅" ) );
//        kslist.add( new DepartmentIdSwitch( "015",20200611120602L,"骨二科" ) );
//        kslist.add( new DepartmentIdSwitch( "016",20200611120702L,"检验科" ) );
//        kslist.add( new DepartmentIdSwitch( "017",20200611120802L,"二楼中医" ) );
//        kslist.add( new DepartmentIdSwitch( "018",20200611120803L,"内二科" ) );
//        kslist.add( new DepartmentIdSwitch( "019",20200611124403L,"妇科" ) );
//        kslist.add( new DepartmentIdSwitch( "020",20200611124503L,"产房" ) );
//        kslist.add( new DepartmentIdSwitch( "021",20200611124504L,"透析室" ) );
//        kslist.add( new DepartmentIdSwitch( "022",20200611124604L,"内一科" ) );
//        kslist.add( new DepartmentIdSwitch( "023",20200611124704L,"内三科" ) );
//        kslist.add( new DepartmentIdSwitch( "024",20200611124705L,"供应室" ) );
//        kslist.add( new DepartmentIdSwitch( "025",20200611124905L,"手术室" ) );
//        kslist.add( new DepartmentIdSwitch( "026",20200611125005L,"骨一科" ) );
//        kslist.add( new DepartmentIdSwitch( "027",20200611125105L,"外科" ) );
//        kslist.add( new DepartmentIdSwitch( "028",20200611125106L,"发热门诊" ) );
//        kslist.add( new DepartmentIdSwitch( "029",20200611125206L,"肛肠门诊" ) );
//        kslist.add( new DepartmentIdSwitch( "030",20200611125306L,"药剂科" ) );
//        kslist.add( new DepartmentIdSwitch( "031",20200611125406L,"公共区域" ) );
        // 沧州疾控中心科室
//        kslist.add( new DepartmentIdSwitch( "001",200731142720187L,"性病艾滋病咨询室" ) );
//        kslist.add( new DepartmentIdSwitch( "002",200731142756546L,"结核病实验东室" ) );
//        kslist.add( new DepartmentIdSwitch( "003",200731143305495L,"结核病实验西室" ) );
//        kslist.add( new DepartmentIdSwitch( "004",200731143324641L,"麻疹实验室" ) );
//        kslist.add( new DepartmentIdSwitch( "005",200731143349981L,"细菌实验室" ) );
//        kslist.add( new DepartmentIdSwitch( "006",200731143409843L,"艾滋病实验室" ) );
//        kslist.add( new DepartmentIdSwitch( "007",007L,"接种门诊" ) );
//        kslist.add( new DepartmentIdSwitch( "008",200731143538597L,"免疫规划科" ) );
        // 市五院
        kslist.add( new DepartmentIdSwitch( "001",200814173826981L,"感染一科" ) );
        kslist.add( new DepartmentIdSwitch( "002",200814173900217L,"感染三科" ) );
        kslist.add( new DepartmentIdSwitch( "003",200814173913744L,"感染四科" ) );
        kslist.add( new DepartmentIdSwitch( "004",200814173928579L,"感染五科" ) );
        kslist.add( new DepartmentIdSwitch( "005",200814173943994L,"感染六科" ) );
        kslist.add( new DepartmentIdSwitch( "006",200814173959639L,"感染七科" ) );
        kslist.add( new DepartmentIdSwitch( "007",200814174807232L,"妇产科" ) );
        kslist.add( new DepartmentIdSwitch( "008",200814174820219L,"放射科1" ) );
        kslist.add( new DepartmentIdSwitch( "009",200814174835419L,"内镜科" ) );
        kslist.add( new DepartmentIdSwitch( "010",200814174853516L,"功能科" ) );
        kslist.add( new DepartmentIdSwitch( "011",200814174906037L,"检验科" ) );
        kslist.add( new DepartmentIdSwitch( "012",200814174926394L,"口腔科" ) );
        kslist.add( new DepartmentIdSwitch( "013",200814174944187L,"肝病门诊" ) );
        kslist.add( new DepartmentIdSwitch( "014",200814175001852L,"急诊科" ) );
        kslist.add( new DepartmentIdSwitch( "015",200814175026659L,"妇产科门诊" ) );
        kslist.add( new DepartmentIdSwitch( "016",200814181043964L,"内一科" ) );
        kslist.add( new DepartmentIdSwitch( "017",200814175139351L,"内二科" ) );
        kslist.add( new DepartmentIdSwitch( "018",200814175225461L,"康复科" ) );
        kslist.add( new DepartmentIdSwitch( "019",200814175252426L,"理疗科" ) );
        kslist.add( new DepartmentIdSwitch( "020",200814175313684L,"外科门诊" ) );
        kslist.add( new DepartmentIdSwitch( "021",200814175338446L,"肿瘤科门诊" ) );
        kslist.add( new DepartmentIdSwitch( "022",200814175402137L,"介入科门诊" ) );
        kslist.add( new DepartmentIdSwitch( "023",200814175435649L,"发热门诊" ) );
        kslist.add( new DepartmentIdSwitch( "024",200814175513864L,"感染二科" ) );
        kslist.add( new DepartmentIdSwitch( "025",200814175528850L,"外科" ) );
        kslist.add( new DepartmentIdSwitch( "026",200814175537604L,"儿科" ) );
        kslist.add( new DepartmentIdSwitch( "027",200814175611074L,"结核一科" ) );
        kslist.add( new DepartmentIdSwitch( "028",200814175628525L,"结核二科" ) );
        kslist.add( new DepartmentIdSwitch( "029",200814175648204L,"结核三科" ) );
        kslist.add( new DepartmentIdSwitch( "030",200814175700784L,"ICU" ) );
        kslist.add( new DepartmentIdSwitch( "031",200814175719738L,"感染十科" ) );
        kslist.add( new DepartmentIdSwitch( "032",200814175748084L,"导管室" ) );
        kslist.add( new DepartmentIdSwitch( "033",200814175811639L,"手麻科" ) );
        kslist.add( new DepartmentIdSwitch( "034",200814175848402L,"放射科2" ) );
        kslist.add( new DepartmentIdSwitch( "035",200814175914721L,"结核门诊" ) );
        kslist.add( new DepartmentIdSwitch( "036",200814175935809L,"支气管镜室" ) );
        kslist.add( new DepartmentIdSwitch( "037",200814180101412L,"国医堂" ) );
        kslist.add( new DepartmentIdSwitch( "038",200814180140276L,"洗消供应室" ) );
        kslist.add( new DepartmentIdSwitch( "039",200814180356301L,"肿瘤科" ) );
        kslist.add( new DepartmentIdSwitch( "040",200814180426536L,"介入医学科" ) );
        kslist.add( new DepartmentIdSwitch( "041",200814180446603L,"体检中心" ) );
        kslist.add( new DepartmentIdSwitch( "042",200814180519869L,"公共一区" ) );
        kslist.add( new DepartmentIdSwitch( "043",200814180537613L,"公共二区" ) );
        kslist.add( new DepartmentIdSwitch( "044",200814180556919L,"中西医结合科" ) );
        kslist.add( new DepartmentIdSwitch( "045",200814180609910L,"药剂科" ) );
        kslist.add( new DepartmentIdSwitch( "046",200814180625301L,"病理科" ) );
        kslist.add( new DepartmentIdSwitch( "047",200814180638501L,"感染门诊" ) );
        kslist.add( new DepartmentIdSwitch( "048",200814180720219L,"发热2病区" ) );
        kslist.add( new DepartmentIdSwitch( "049",200814180735577L,"发热1病区" ) );
        kslist.add( new DepartmentIdSwitch( "050",200814180748499L,"发热门诊2" ) );
        kslist.add( new DepartmentIdSwitch( "051",200814180805479L,"发热3病区" ) );
        kslist.add( new DepartmentIdSwitch( "052",200814180820767L,"发热4病区" ) );
        kslist.add( new DepartmentIdSwitch( "053",200814180835163L,"检验科B区" ) );
        kslist.add( new DepartmentIdSwitch( "054",200814180850387L,"卫生局" ) );
        kslist.add( new DepartmentIdSwitch( "055",200814180907636L,"1号楼ICU" ) );


        System.out.println( "   科室数量： " + kslist.size() );

        // 医废类型转换
        List<YFTypeIdSwitch> yftypelist = new ArrayList<>();
        yftypelist.add( new YFTypeIdSwitch("001","1","病理性" ) );
        yftypelist.add( new YFTypeIdSwitch("002","2","损伤性" ) );
        yftypelist.add( new YFTypeIdSwitch("003","3","感染性" ) );
        yftypelist.add( new YFTypeIdSwitch("004","4","药物性" ) );
        yftypelist.add( new YFTypeIdSwitch("005","5","化学性" ) );
        yftypelist.add( new YFTypeIdSwitch("006","6","胎盘" ) );

        // 医废状态转换
        List<YFStatusSwitch> yfstatuslist = new ArrayList<>();
        yfstatuslist.add( new YFStatusSwitch("01","10","已收集" ) );
        yfstatuslist.add( new YFStatusSwitch("02","20","已入库" ) );
        yfstatuslist.add( new YFStatusSwitch("03","30","已出库" ) );


        // 查询旧平台照片
        List<OldPhoto> oldphotolist = yfTagService.getAllOldPhoto( );

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        System.out.println( "   照片数量： " + oldphotolist.size() );


//        // 黄骅神农居医院
//        // 收集员
//        List<UserIdSwitch> colluserlist = new ArrayList<>();
//        colluserlist.add( new UserIdSwitch("1",135L ) );
//        // 入库员
//        List<UserIdSwitch> inuserlist = new ArrayList<>();
//        inuserlist.add( new UserIdSwitch("2",136L ) );
//        // 出库员
//        List<UserIdSwitch> outuserlist = new ArrayList<>();
//        outuserlist.add( new UserIdSwitch("2",137L ) );
//        // 黄骅神农居暂存点id
//        Long stagingId = 263L;


        // 沧州疾控中心
        // 收集员
//        List<UserIdSwitch> colluserlist = new ArrayList<>();
//        colluserlist.add( new UserIdSwitch("1",432L ) );
//        // 入库员
//        List<UserIdSwitch> inuserlist = new ArrayList<>();
//        inuserlist.add( new UserIdSwitch("2",433L ) );
//        // 出库员
//        List<UserIdSwitch> outuserlist = new ArrayList<>();
//        outuserlist.add( new UserIdSwitch("3",434L ) );
//        // 沧州疾控中心暂存点id
//        Long stagingId = 305L;


        // 石家庄市五院
        // 收集员
        List<UserIdSwitch> colluserlist = new ArrayList<>();
        colluserlist.add( new UserIdSwitch("1",435L ) );
        colluserlist.add( new UserIdSwitch("2",436L ) );
        colluserlist.add( new UserIdSwitch("3",437L ) );
        colluserlist.add( new UserIdSwitch("9",438L ) );
        // 入库员
        List<UserIdSwitch> inuserlist = new ArrayList<>();
        inuserlist.add( new UserIdSwitch("6",439L ) );
        // 出库员
        List<UserIdSwitch> outuserlist = new ArrayList<>();
        outuserlist.add( new UserIdSwitch("6",439L ) );
        outuserlist.add( new UserIdSwitch("7",440L ) );
        // 沧州疾控中心暂存点id
        Long stagingId = 13002191301L;


        // LIMIT 5,10; // 检索记录行 6-15
        int startIndex = 0;
        int yfLength = 500;


        // 医废总条数
        int yfnum = yfTagService.getAllOldYFNum( );


        // 批量添加，每次500条
        while( startIndex <= yfnum ){

            List<OldYF> oldyflist = yfTagService.getOldYF( startIndex,yfLength );

            System.out.println( "   医废数量： " + oldyflist.size() );

            // 装转换格式后的医废
            List<YfTag> yfTagList = new ArrayList<>();

            // 医废数据转换
            if( oldyflist != null && !oldyflist.isEmpty() ){

                for (int i = 0; i < oldyflist.size(); i++) {

                    // 旧平台医废
                    OldYF oldYF = oldyflist.get(i);


                    // 新平台医废 必要字段:
                    YfTag yfTag = new YfTag();
                    yfTag.setCodeid( oldYF.getCodeId() );
                    // 暂存点
                    yfTag.setStagingId( stagingId );
                    // 收集员id
                    if( !StringUtils.isEmpty(oldYF.getHealthPer()) ){
                        for (int j = 0; j < colluserlist.size(); j++) {
                            if( colluserlist.get(j).getOldUserId().equals( oldYF.getHealthPer() ) ){
                                yfTag.setCollectUserId( colluserlist.get(j).getNewUserId() );
                                break;
                            }
                        }
                    }else{
                        yfTag.setCollectUserId( null );
                    }

                    // 科室id
                    for (int j = 0; j < kslist.size(); j++) {
                        if( kslist.get(j).getOldDeptId().equals( oldYF.getSourceOffice() ) ){
                            yfTag.setSourceDeptId( kslist.get(j).getNewDeptId() );
                            break;
                        }
                    }
                    // 医废类型
                    for (int j = 0; j < yftypelist.size() ; j++) {
                        if( yftypelist.get(j).getOldYFTypeId().equals( oldYF.getTrashType() ) ){
                            yfTag.setTrashType( yftypelist.get(j).getNewYFTypeId() );
                            break;
                        }
                    }
                    // 医废重量
                    yfTag.setWeight( Double.parseDouble( oldYF.getTrashWeight() ) );
                    // 扫描科室时间
                    yfTag.setScanDeptDate(oldYF.getDepartDate());
                    // 收集时间
                    yfTag.setCollectUpdateDate( oldYF.getColletDate() );
                    // 入库员id
                    if( !StringUtils.isEmpty(oldYF.getTempPer()) ){
                        for (int j = 0; j < inuserlist.size(); j++) {
                            if( inuserlist.get(j).getOldUserId().equals( oldYF.getTempPer() ) ){
                                yfTag.setIntoUserId( inuserlist.get(j).getNewUserId() );
                                break;
                            }
                        }
                    }else{
                        yfTag.setIntoUserId( null );
                    }

                    // 入库时间
                    yfTag.setIntoDate( oldYF.getHoldDate() );
                    // 出库员id
                    if( !StringUtils.isEmpty(oldYF.getCardId()) ){
                        for (int j = 0; j < outuserlist.size(); j++) {
                            if( outuserlist.get(j).getOldUserId().equals( oldYF.getCardId() ) ){
                                yfTag.setOutUserId( outuserlist.get(j).getNewUserId() );
                                break;
                            }
                        }
                    }else{
                        yfTag.setOutUserId( null );
                    }

                    // 出库时间
                    yfTag.setOutDate( oldYF.getCarDate() );
                    // 上传时间
                    yfTag.setCreateTime( oldYF.getUploadDate() );
                    // 医废状态
                    for (int j = 0; j < yfstatuslist.size() ; j++) {
                        if( yfstatuslist.get(j).getOldYFStatus().equals( oldYF.getBcstatis() ) ){
                            yfTag.setTrashStatus( yfstatuslist.get(j).getNewYFStatus() );
                            break;
                        }
                    }
                    // 上传方式
                    yfTag.setUpdateWay( "0" );
                    // 医废照片 img1 img1_date
                    for (int j = 0; j < oldphotolist.size(); j++) {
                        if( oldphotolist.get(j).getBarcodeNo().equals( oldYF.getCodeId() ) ){     // 比对条码，获取图片路径
//                        yfTag.setImg1( oldphotolist.get(j).getFilePath() );
                            // 黄骅神农居医院
//                            yfTag.setImg1( "/profile/medical_snjyy_img/" + oldphotolist.get(j).getFileName() );
                            // 沧州疾控中心
//                            yfTag.setImg1( "/profile/medical_czjk_img/" + oldphotolist.get(j).getFileName() );
                            // 石家庄市第五医院
                            yfTag.setImg1( "/profile/medical_sjzwy_img/" + sdf.format(oldphotolist.get(j).getBarcodeDate()) + "/" + oldphotolist.get(j).getFileName() );
                            yfTag.setImg1Date( oldphotolist.get(j).getBarcodeDate() );
                            break;
                        }
                    }

                    yfTagList.add( yfTag );
                }


                // 批量添加医废（用于数据迁移）
                yfTagService.saveYfTagList( yfTagList );

            }


            startIndex = startIndex + 500;

        }


        return "1";
    }



    // 大批量添加医废测试数据接口
    //590e1a0a-4de9-44b3-860e-77227c6d0098
    @RequestMapping("/insertYFBatchData")
    @ResponseBody
    public ResponseData insertYFBatchData(){
        String nn = ServletUtils.getRequest().getParameter("num");
        int num;
        try{
            num = Integer.parseInt(nn.trim());
            if( num > 50 || num < 1 ){
                return ResponseData.failureN("num不能小于1,不能大于50");
            }
        }catch (Exception e){
            return ResponseData.failureN("请正确填写num，不大于50的整数");
        }
        num = num * 10000;

        // 暂存点 -- 采集员 -- 入库员  --  出库员
        List<Long[]> idlist = new ArrayList<>();
        idlist.add( new Long[]{ 209L , 101L, 114L, 175L } );
        idlist.add( new Long[]{ 222L , 102L, 116L, 176L } );
        idlist.add( new Long[]{ 246L , 111L, 142L, 143L } );
        idlist.add( new Long[]{ 246L , 122L, 115L, 110L } );
        idlist.add( new Long[]{ 248L , 163L, 164L, 165L } );
        idlist.add( new Long[]{ 259L , 177L, 178L, 179L } );
        idlist.add( new Long[]{ 258L , 123L, 170L, 171L } );
        idlist.add( new Long[]{ 308L , 167L, 168L, 169L } );
        idlist.add( new Long[]{ 309L , 172L, 173L, 174L } );

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createDate = new Date();

        // 提交医废的list
        List<YfTag> list = new ArrayList();

        for (int i = 0; i < num; i++) {
            YfTag yf = new YfTag();
            yf.setCodeid( new Rules().longBarcode().replace("yl","test") );
            // 医废状态   10：四分之一    20：四分之一     30：四分之二
            int ts =  new Random().nextInt( 4 );
            if( ts == 0 ){
                yf.setTrashStatus("10");
            }else if( ts == 1 ){
                yf.setTrashStatus("20");
            }else{
                yf.setTrashStatus("30");
            }
            // 袋数、重量
            yf.setBag(1L);
            yf.setWeight( (new Random().nextInt( 1000 ) + 1) / 100D );
            // 已出库袋数、已出库重量
            if( yf.getTrashStatus().equals("30") ){
                yf.setOutBag(1L);
                yf.setOutWeight( yf.getWeight() );
            }else{
                yf.setOutBag(0L);
                yf.setOutWeight( 0.0D );
            }
            // 医废类型、上传方式
            yf.setTrashType( (new Random().nextInt( 6 ) + 1) + "" );
            yf.setUpdateWay("99");
            // 暂存点、收集人、入库人、出库人
            // 从 idlist 随机取1条
            int pos = new Random().nextInt( idlist.size() );      // 介于[0,n)
            yf.setStagingId( idlist.get(pos)[0] );
            if( yf.getTrashStatus().equals("10") ){     // 收集
                // 收集人
                yf.setCollectUserId( idlist.get(pos)[1] );
                // 收集时间   从现在算起 2天内
                Date colldate = new Date( (new Date().getTime() - Long.parseLong(new Random().nextInt( 3600000 * 48 ) + "")) );
                yf.setCollectUpdateDate( colldate );
            }else if ( yf.getTrashStatus().equals("20") ){    // 入库
                // 入库人
                yf.setIntoUserId( idlist.get(pos)[2] );
                // 入库时间   从现在算起 2天内
                Date intodate = new Date( (new Date().getTime() - Long.parseLong(new Random().nextInt( 3600000 * 48 ) + "")) );
                yf.setIntoDate( intodate );
                // 收集人
                yf.setCollectUserId( idlist.get(pos)[1] );
                // 收集时间   入库时间往前推 2天内
                Date colldate = new Date( (yf.getIntoDate().getTime() - Long.parseLong(new Random().nextInt( 3600000 * 48 ) + "")) );
                yf.setCollectUpdateDate( colldate );
            }else if ( yf.getTrashStatus().equals("30") ){    // 出库
                // 出库人
                yf.setOutUserId( idlist.get(pos)[3] );
                // 出库时间   从现在算起 2天内
                Date outdate = new Date( (new Date().getTime() - Long.parseLong(new Random().nextInt( 3600000 * 48 ) + "")) );
                yf.setOutDate( outdate );
                // 入库人
                yf.setIntoUserId( idlist.get(pos)[2] );
                // 入库时间   从出库算起 2天内
                Date intodate = new Date( (yf.getOutDate().getTime() - Long.parseLong(new Random().nextInt( 3600000 * 48 ) + "")) );
                yf.setIntoDate( intodate );
                // 收集人 = 入库人
                yf.setCollectUserId( yf.getIntoUserId() );
                // 收集时间 = 入库时间
                yf.setCollectUpdateDate( yf.getIntoDate() );
            }
            // 创建时间、更新时间
            yf.setCreateTime(createDate);
            yf.setUpdateTime(new Date());


            list.add(yf);
            if( list.size() == 1000 || i == (num - 1) ){
                // 大批量添加测试数据到数据库
                yfTagService.insertYFBatchData(list);
                list.clear();
            }
            
        }

        return ResponseData.successY("添加 " + num  + " 条数据成功！");
    }




    static int sheetNum = 0;    // 第几个sheet页
    static Date nowdate;
    // static String password = "111111";     // 初始密码
    static String password = "yftb666*";     // 初始密码



    // 读excel导入机构、科室、用户
    //655a2910-5d1a-4091-a4f0-62c7a33a31fe
    @GetMapping("/fromExcelImportDeptAndUser")
    @ResponseBody
    public String fromExcelImportDeptAndUser(){


        passwordService = new SysPasswordService();


        nowdate = new Date();


        try{
            HSSFWorkbook hssfbook = new HSSFWorkbook(
                    new FileInputStream("C:\\Users\\Administrator\\Desktop\\12345.xls") );
            // 读取表格的第一个sheet页
            HSSFSheet sheet = hssfbook.getSheetAt( sheetNum );
            // 总共有多少行,从0开始
            int totalRows = sheet.getLastRowNum();
            System.out.println("  ======= 总共有多少行:" + totalRows );


            // 循环输出表格中的内容,赋值bean类
            for (int i = 1; i <= totalRows; i++) {  // 从第二行开始取
                Row row = sheet.getRow(i);
                // 处理空行
                if(row == null || row.getCell(17) == null ||  StringUtils.isEmpty(row.getCell(17).toString().trim())  ){
                    continue ;
                }
                if( (row.getCell(2) == null && row.getCell(17) == null) ||
                        ( StringUtils.isEmpty(row.getCell(2).toString().trim()) && StringUtils.isEmpty(row.getCell(17).toString().trim()) ) ){
                    System.out.println("  ======= break的行数（index + 1）: " + ( i + 1 )  );
                    break;
                }

                System.out.println("  ======= 序号： " + (int)Double.parseDouble(row.getCell(0).toString().trim())
                        + "\t\t机构名称: " + row.getCell(2).toString().trim()
                        + "\t\t\t唯一识别码： " + row.getCell(17).toString().trim()  );


                // 转换等级、机构类型、用户角色
                String ospitalGrade = null;
                String deptType = null;
                Long roleId = null;
                String gradeName = row.getCell(3).toString().trim();
                //
//                if( gradeName.equals("诊所") ){
//                    ospitalGrade = "20";
//                    deptType = "330";
//                    roleId = 170L;
//                }else if( gradeName.equals("村卫生室") ){
//                    ospitalGrade = "30";
//                    deptType = "340";
//                    roleId = 190L;
//                }else if( gradeName.equals("社区卫生服务站") ){
//                    ospitalGrade = "40";
//                    deptType = "350";
//                    roleId = 160L;
//                }

                // 机构类型统一成：  其它机构（原 乡镇卫生院的） 320      角色id ：用乡镇卫生院管理员的  150
                if( gradeName.equals("诊所") ){
                    ospitalGrade = "20";
                    deptType = "320";
                    roleId = 150L;
                }else if( gradeName.equals("村卫生室") ){
                    ospitalGrade = "30";
                    deptType = "320";
                    roleId = 150L;
                }else if( gradeName.equals("社区卫生服务站") ){
                    ospitalGrade = "40";
                    deptType = "320";
                    roleId = 150L;
                }else if( gradeName.equals("市级医院") ){
                    ospitalGrade = "0";
                    deptType = "270";
                    roleId = 90L;
                }else if( gradeName.equals("省级医院") ){
                    ospitalGrade = "0";
                    deptType = "220";
                    roleId = 60L;
                }


                // 父id、父id群、地区id
                String countyName = sheet.getRow(i).getCell(1).toString().trim();
                Long parentId = null;
                String ancestors = null;
                Integer districtsId = null;
                if( countyName.equals("石家庄循环化工园区") ){
                    parentId = 342L;
                    ancestors = "0,100,318,319,342";
                    districtsId = 130172;
                }else if( countyName.equals("赵县")){
                    parentId = 340L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130133;
                }else if( countyName.equals("行唐县")){
                    parentId = 332L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130125;
                }else if( countyName.equals("鹿泉区")){    // 4
                    parentId = 327L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130110;
                }else if( countyName.equals("栾城区")){
                    parentId = 328L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130111;
                }else if( countyName.equals("高邑县")){     // 6
                    parentId = 334L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130127;
                }else if( countyName.equals("灵寿县")){
                    parentId = 333L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130126;
                }else if( countyName.equals("平山县")){     // 8
                    parentId = 338L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130131;
                }else if( countyName.equals("藁城区")){
                    parentId = 326L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130109;
                }else if( countyName.equals("长安区")){     // 10
                    parentId = 321L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130102;
                }else if( countyName.equals("新乐市")){
                    parentId = 330L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130184;
                }else if( countyName.equals("正定县")){     // 12
                    parentId = 320L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130123;
                }else if( countyName.equals("无极县")){
                    parentId = 337L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130130;
                }else if( countyName.equals("元氏县")){     // 14
                    parentId = 339L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130132;
                }else if( countyName.equals("新华区")){
                    parentId = 323L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130105;
                }else if( countyName.equals("裕华区")){     // 16
                    parentId = 325L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130108;
                }else if( countyName.equals("桥西区")){
                    parentId = 322L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130104;
                }else if( countyName.equals("高新区")){     // 18
                    parentId = 341L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130171;
                }else if( countyName.equals("井陉县")){     // 19
                    parentId = 331L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130121;
                }else if( countyName.equals("井陉矿区")){     // 20
                    parentId = 324L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130107;
                }else if( countyName.equals("晋州市")){     // 21
                    parentId = 329L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130183;
                }else if( countyName.equals("赞皇县")){     // 22   没有 深泽
                    parentId = 336L;
                    ancestors =  ("0,100,318,319," + parentId ).replace("L","") ;
                    districtsId = 130129;
                }


                // 医院、暂存点、科室、用户-管理员、用户-填报员、用户-角色关联

                // 医院
                SysDept hospital = new SysDept();
                hospital.setDeptId( Long.parseLong( row.getCell(17).toString().trim().replace("'","") ) );
                hospital.setDeptName( row.getCell(2).toString().trim() );
                hospital.setParentId(parentId);     // 父id
                hospital.setAncestors(ancestors);     // 父id群
                hospital.setOrderNum("99");     // 排序
                hospital.setStatus("0");
                hospital.setDelFlag("0");
                hospital.setCreateBy("admin");
                hospital.setCreateTime( nowdate );
                hospital.setHospitalGrade(ospitalGrade);        // 医院等级
                hospital.setDeptType(deptType);             // 机构类型  320 : 乡镇卫生院  310 社区服务中心  330 诊所   340 村卫生室
                hospital.setDistrictsId(districtsId);


                // 暂存点
                SysDept staging = new SysDept();
                staging.setDeptId( Long.parseLong( row.getCell(17).toString().trim().replace("'","") + "01" ) );   // 医院id + 01
                staging.setDeptName( row.getCell(2).toString().trim() + "医废暂存点" );
                staging.setParentId( hospital.getDeptId() );     // 父id  --  取医疗机构id
                staging.setAncestors(ancestors + "," + hospital.getDeptId() );     // 父id群 拼接 ， 医院的父id群
                staging.setOrderNum("99");     // 排序
                staging.setStatus("0");
                staging.setDelFlag("0");
                staging.setCreateBy("admin");
                staging.setCreateTime( nowdate );
                staging.setHospitalGrade("0");        // 医院等级 -- 取未定级
                staging.setDeptType("400");             // 机构类型  -- 暂存点
                staging.setDistrictsId(districtsId);


                // 科室
                YfDept yfDept = new YfDept();
                yfDept.setDeptId( Long.parseLong(hospital.getDeptId() + "000001") );
                yfDept.setHospitalId(hospital.getDeptId());
                yfDept.setType("10");   // 填 科室
                yfDept.setStandardDeptCode("A02");
                yfDept.setDeptName("全科");
                yfDept.setDeptUserName("医生");
                yfDept.setGroupNo(1);
                yfDept.setGroupName(hospital.getDeptName());
                yfDept.setBuildingNo(1);
                yfDept.setStatus("0");
                yfDept.setDelFlag("0");
                yfDept.setCreateBy("admin");
                yfDept.setCreateTime( nowdate );


                // 用户-管理员、用户-填报员、用户-角色关联
                SysUser manageruser = new SysUser();
                manageruser.setUserId( Long.parseLong(hospital.getDeptId() + "001") );  // 医院id + 001
                manageruser.setLoginName( hospital.getDeptId() + "001" );  // 医院id + 001
                manageruser.setDeptId( hospital.getDeptId() );
                manageruser.setUserName("管理员");
                manageruser.setSex("2");
                manageruser.setStatus("0");
                manageruser.setDelFlag("0");
                manageruser.setCreateBy("admin");
                manageruser.setCreateTime( nowdate );
                manageruser.setLoginType("200");
                // 盐、密码
                manageruser.setSalt(ShiroUtils.randomSalt());
                manageruser.setPassword(password);
                manageruser.setPassword(passwordService.encryptPassword(manageruser.getLoginName(), manageruser.getPassword(), manageruser.getSalt()));

                //  用户-角色关联 - 管理员
                manageruser.setRoleIds( new Long[]{roleId} );



                // 用户-填报员
                SysUser colluser = new SysUser();
                colluser.setUserId( Long.parseLong(hospital.getDeptId() + "002") );  // 医院id + 002
                colluser.setLoginName( hospital.getDeptId() + "002" );  // 医院id + 002
                colluser.setDeptId( staging.getDeptId() );
                colluser.setUserName("填报员");
                colluser.setSex("2");
                colluser.setStatus("0");
                colluser.setDelFlag("0");
                colluser.setCreateBy("admin");
                colluser.setCreateTime( nowdate );
                colluser.setLoginType("300,400");
                // 盐、密码
                colluser.setSalt(ShiroUtils.randomSalt());
                colluser.setPassword(password);
                colluser.setPassword(passwordService.encryptPassword(colluser.getLoginName(), colluser.getPassword(), colluser.getSalt()));

                //  用户-角色关联 - 填报员
                colluser.setRoleIds( new Long[]{210L} );


                // 添加医院、暂存点、管理员、填报员、两个用户角色关联表
                if( true ){
                    // 医院、暂存点
                    sysDeptService.insertDept( hospital );
                    sysDeptService.insertDept( staging );

                    // 默认的科室
                    yfDeptService.insertYfDept(yfDept);


                    // 用户 - 管理员、填报员
                    sysUserService.insertUser( manageruser );
                    sysUserService.insertUser( colluser );

                }

            }

        } catch (Exception e) {
            e.printStackTrace();

        }



        return "1";
    }




    // iPhone - APP 开关
    //cd18c3cc-17eb-413e-a494-5344782fb0f8
    @RequestMapping("/getIPhoneAPPRegisterSwitch")
    @ResponseBody
    public String getIPhoneAPPRegisterSwitch(String iPhoneYFAPP){

        if( StringUtils.isEmpty(iPhoneYFAPP) || !iPhoneYFAPP.equals("true") ){
            return "false";
        }

        // IPoneAPP - 开关
        String iPhoneAPPSwitch = configService.selectConfigByKey("yf.iPhoneAPP.registerSwitch");
        // System.out.println("   ========  " + iPhoneAPPSwitch  );
        if( !StringUtils.isEmpty(iPhoneAPPSwitch) && iPhoneAPPSwitch.equals("true") ){
            return "true";
        }
        return "false";
    }



    // iPhone - APP 用户注册
    //ac6bbb12-a1bf-4a0d-bee5-44749212fd8b
    @RequestMapping("/registerIPhoneAPPUser")
    @ResponseBody
    public AjaxResult registerIPhoneAPPUser(String loginName, String userName, String email, String phonenumber, String sex, String password ){

        if(StringUtils.isEmpty(loginName)){
            return error("登录名称不能为空");
        }
        if(StringUtils.isEmpty(userName)){
            return error("用户名称不能为空");
        }
        if(StringUtils.isEmpty(email)){
            return error("邮箱不能为空");
        }
        if(StringUtils.isEmpty(phonenumber)){
            return error("手机号不能为空");
        }
        if(StringUtils.isEmpty(sex)){
            return error("性别不能为空");
        }
        if(StringUtils.isEmpty(password)){
            return error("密码不能为空");
        }

        if(loginName.trim().length() > 25 ){
            return error("登录名称不能超过25位");
        }
        if(userName.trim().length() > 25 ){
            return error("用户名称不能超过25位");
        }
        if(email.trim().length() > 100 ){
            return error("邮箱不能超过100位");
        }
        if(phonenumber.trim().length() > 18 ){
            return error("手机号不能超过18位");
        }
        if(sex.trim().length() > 2 ){
            return error("性别不能超过2位");
        }
        if(password.trim().length() > 30 ){
            return error("密码不能超过30位");
        }


        SysUser user = new SysUser();
        user.setLoginName(loginName);
        user.setUserName(userName);
        user.setEmail(email);
        user.setPhonenumber(phonenumber);
        user.setSex(sex);
        user.setPassword(password);

        // 其它字段
        user.setDeptId(50001L);
        user.setRoleIds(new Long[]{210L});
        user.setLoginType("200");
        user.setRemark("苹果用户注册");

        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
//        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
//        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
//        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy("admin");
        return toAjax(userService.insertUser(user));
    }



    // 批量修改密码 -- http://localhost:1082/client/BatchUpdatePassword
    @GetMapping("/BatchUpdatePassword")
    @ResponseBody
    public String BatchUpdatePassword(){


        passwordService = new SysPasswordService();


        nowdate = new Date();


        try{
            HSSFWorkbook hssfbook = new HSSFWorkbook(
                    new FileInputStream("C:\\Users\\Administrator\\Desktop\\password.xls") );
            // 读取表格的第一个sheet页
            HSSFSheet sheet = hssfbook.getSheetAt( sheetNum );
            // 总共有多少行,从0开始
            int totalRows = sheet.getLastRowNum();
            System.out.println("  ======= 总共有多少行:" + totalRows );


            // 循环输出表格中的内容,赋值bean类
            for (int i = 1; i <= totalRows; i++) {  // 从第二行开始取
                Row row = sheet.getRow(i);
                // 处理空行
                if(row == null || row.getCell(0) == null ||  StringUtils.isEmpty(row.getCell(0).toString().trim())
                        || row.getCell(1) == null ||  StringUtils.isEmpty(row.getCell(1).toString().trim())
                        || row.getCell(2) == null ||  StringUtils.isEmpty(row.getCell(2).toString().trim()) ){
                    continue ;
                }

                System.out.println("  ======= excel 索引: " + ( i + 1 )  + "  用户序号：" + row.getCell(0).toString().trim()
                                    + "    登录名称：" + row.getCell(1).toString().trim()
                                    + "    密码：" + row.getCell(2).toString().trim()
                                    + "    用户姓名：" + row.getCell(3).toString().trim() );


                Map<String, Object> param = new HashMap<String, Object>();
                param.put("userId", row.getCell(0).toString().trim());
                param.put("loginName", row.getCell(1).toString().trim());
                param.put("password", row.getCell(2).toString().trim());
                HttpResponse httpResponse = HttpRequest.post("http://cz.yf.hblshq.cn:8091/system/user/resetPwd")
                        .header("Cookie","JSESSIONID=66c33a83-17f2-452d-86d1-4e52f3ede4fc")
                        .form(param)
                        .execute();
                int status = httpResponse.getStatus();
                if (status == 200) {    // 请求成功
                    String result = httpResponse.body();
                    System.out.println(" ==========================  " + result );
                }

            }

        } catch (Exception e) {
            e.printStackTrace();

        }



        return "1";
    }






}
